package com.yonhee.datastructure.arrayList;

import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

/**
 * 自定义动态数组
 */
public class MyArrayList implements Iterable<Integer> {
    private int[] data = {};
    private int size = 0; // 逻辑大小
    private static final int capacity = 10; // 实际容量

    public void add(int element) {
//        data[size] = element;
//        size++;

        add(size, element);
    }

    public void add(int index, int element) {
        checkAndGrow();

        // 原始添加逻辑
        if (index >= 0 && index < size) {
            System.arraycopy(data, index, data, index + 1, size - index);
        }

        data[index] = element;
        size++;
    }

    /**
     * 检查是否需要扩容
     */
    private void checkAndGrow() {
        if (data.length == 0) {
            data = new int[capacity];
        }
        // 判断是否扩容
        else if (size == capacity) {
            // 数组放满，开始扩容
            int[] newArray = new int[capacity + capacity >> 1];
            System.arraycopy(data, 0, newArray, 0, size);
            data = newArray;
        }

    }

    public int remove(int index) {
        int removed = data[index];
        if (index < size - 1) {
            System.arraycopy(data, index + 1, data, index, size - index - 1);
        }
        size--;
        return removed;
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is illegal");
        }
        return data[index];
    }

    public void foreach(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(data[i]);
        }
    }

    public void forEach() {
        for (int i = 0; i < size; i++) {
            System.out.println(data[i]);
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < size;
            }

            @Override
            public Integer next() {
                return data[index++];
            }
        };
    }

    public IntStream stream() {
        return IntStream.of(data) // of()会返回整个数组，包含没有赋值的部分
                .limit(size);
    }
}
